package qc.module.cms.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import qc.common.core.enums.CmsArticleOperateTypeEnum;
import qc.common.core.unify.QCUnifyReturnValue;
import qc.common.core.utils.DateUtil;
import qc.module.cms.dto.article.ArticleLogDto;
import qc.module.cms.entity.ArticleLog;
import qc.module.cms.mapper.ArticleLogMapper;
import qc.module.cms.repository.ArticleLogRepository;
import qc.module.platform.dto.uac.UacUserInfoDto;

import java.util.List;

/**
 * ArticleLogService
 *
 * @author QuCheng Tech
 * @since 2023/5/30
 */
@Service
public class ArticleLogService {

    private ArticleLogRepository repository;

    @Autowired
    public void setArticleLogRepository(ArticleLogRepository repository) {
        this.repository = repository;
    }

    /**
     * 添加文章操作日志记录
     *
     * @param articleId   文章ID
     * @param operateType 操作类型
     * @param message     操作消息
     * @param userInfo    操作人信息
     * @return 成功返回null
     * @author QuCheng Tech
     * @since 2023/5/31
     */
    public String add(Integer articleId, CmsArticleOperateTypeEnum operateType, String message, UacUserInfoDto userInfo) {
        ArticleLog en = new ArticleLog();
        en.setAid(articleId);
        en.setTm(DateUtil.getNowDate());
        en.setOp(operateType);
        en.setMsg(message);
        if (userInfo != null)
            en.setUser(userInfo.getName());

        repository.insert(en);

        return QCUnifyReturnValue.Success();
    }

    /**
     * 获取指定ID文章的操作日志
     *
     * @param articleId 文章ID
     * @return 所有操作日志，按时间先后顺序排序
     * @author QuCheng Tech
     * @since 2023/5/31
     */
    public List<ArticleLogDto> getArticleLogs(int articleId) {
        LambdaQueryWrapper<ArticleLog> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ArticleLog::getAid, articleId);
        wrapper.orderByAsc(ArticleLog::getTm);

        List<ArticleLog> ens = repository.selectList(wrapper);

        if (ens != null && ens.size() > 0x0)
            return ArticleLogMapper.MAPPER.toDtoList(ens);

        return null;
    }

    public void deleteArticleLogs(int articleId) {
        LambdaUpdateWrapper<ArticleLog> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(ArticleLog::getAid, articleId);

        repository.delete(wrapper);
    }
}
